package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.util.FileOperateUtil;
import com.fdb.efp.nls.service.dao.AccLedgerDao;
import com.fdb.efp.nls.service.dao.AccLedgerDownloadFileTempDao;
import com.fdb.efp.nls.service.dao.AccLedgerFileTempDao;
import com.fdb.efp.nls.service.domain.AccLedger;
import com.fdb.efp.nls.service.domain.AccLedgerDownloadFileTemp;
import com.fdb.efp.nls.service.domain.AccLedgerFileTemp;
import com.fdb.efp.nls.service.facade.AccLedgerService;
import com.fdb.efp.nls.service.facade.AccoutErroTempService;
import com.fdb.efp.nls.service.vo.AccLedgerVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("accLedgerService")
public class AccLedgerServiceImpl implements AccLedgerService, FrameworkService {
	private static Logger logger = LoggerFactory.getLogger(BatCircleaccServiceImpl.class);

	private static String LEDGER_FILE_NAME = "IFP_UL_0101_OCM_PMS001_";

	private static String DATA_SEPARATOR = "|";// 数据分隔符

	private static String TXT_SUFFIX = ".txt";// txt文件后缀

	@Autowired
	private AccLedgerDao accLedgerDao;
	@Autowired
	private AccLedgerFileTempDao accLedgerFileTempDao;
	@Autowired
	private AccoutErroTempService accoutErroTempService;
	@Autowired
	private AccLedgerDownloadFileTempDao accLedgerDownloadFileTempDao;

	/**
	 * 同步马上的数据 并账文件
	 * 
	 * @description:TODO
	 * @return
	 * @throws Exception
	 * @date:2019年1月3日 上午11:30:49
	 * @author:cenyj
	 */
	public boolean batchAccLedgerFromMaTxt() throws Exception {
		boolean rs = false;
		try {
			// 1读取同步过来的临时表数据
			List<AccLedgerFileTemp> tempList = accLedgerFileTempDao.getAccLedgerFileTempDaoList();
			// 2解析同步过来的临时表数据
			// 3解析出来的数据对应保存到本地表
			// AccLedger accLedgerModel = new AccLedger();
			AccLedgerVO accLedgerModel = new AccLedgerVO();
			if (tempList != null && tempList.size() > 0) {
				for (int i = 0; i < tempList.size(); i++) {
					// fileTemp.getField() 去掉下划线
					String[] strArr = tempList.get(i).getField().split("_");
					StringBuffer stringBuffer = new StringBuffer();
					for (String string : strArr) {
						String upperStr = string.substring(0, 1).toUpperCase() + string.substring(1);
						stringBuffer.append(upperStr);
					}
					String retStr = new String(stringBuffer);
					if (i == 0) {
						Class<AccLedgerVO> clazz = AccLedgerVO.class;
						java.lang.reflect.Method method = clazz.getMethod("set" + retStr, new Class[] { String.class });
						method.invoke(accLedgerModel, tempList.get(i).getFieleValues());
					} else {
						Class<AccLedgerVO> clazz = AccLedgerVO.class;
						java.lang.reflect.Method method = clazz.getMethod("set" + retStr, new Class[] { BigDecimal.class });
						method.invoke(accLedgerModel, new BigDecimal(tempList.get(i).getFieleValues()));
					}
					// 把临时表的值读取出来放到 acc_ledger_file_temp
				}
				int num = insert(accLedgerModel);
				if (num > 0) {
					// 根据tempList.get(i).getFieldName()和acc_ledger_file_temp的NARRATIVE交易描述对应，修改为对应的交易金额
					String changeDate = tempList.get(0).getFieleValues();
					int rsUpdate = accLedgerDownloadFileTempDao.update(changeDate);
					if (rsUpdate > 0) {

					} else {
						String tableName = "AccLedger并账文件表";
						String erroMsg = "";
						String tempTotal = "";
						String acountTotal = "";
						String type = "3";
						String updateDelInster = "新增";
						String no = "";
						String eMsg = "";
						accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);
					}
					// 按要求格式生成txt文件
					getCtrLoanContBatchAppFile();
					rs = true;
				} else {
					rs = false;
					String tableName = "AccLedger并账文件表";
					String erroMsg = "";
					String tempTotal = "";
					String acountTotal = "";
					String type = "3";
					String updateDelInster = "新增";
					String no = "";
					String eMsg = "";
					accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);

					throw new Exception("新增并账文件出错!");
				}
			}
		} catch (

		Exception e) {
			rs = false;
			logger.error("新增数据发生异常!", e);
		}
		return rs;
	}

	public File getCtrLoanContBatchAppFile() {

		File file = null;
		try {
			logger.info("开始读acc_ledger_file_temp表数据.....");
			// 1读取同步过来的临时表数据
			// List<AccLedgerFileTemp> tempList =
			// accLedgerFileTempDao.getAccLedgerFileTempDaoList();
			List<AccLedgerDownloadFileTemp> tempList = accLedgerDownloadFileTempDao.getAccLedgerDownloadFileTempList();
			if (Objects.nonNull(tempList) && tempList.size() > 0) {
				logger.info("查询出[" + tempList.size() + "]条acc_ledger_file_temp表数据");
				// String filePath, List<T> lists, String operation
				String localUploadPath = "f:/";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");// new SimpleDateFormat("yyyyMMddHHmmss");
				String currDate = sdf.format(new Date());
				file = FileOperateUtil.writeTxt(localUploadPath + LEDGER_FILE_NAME + currDate + TXT_SUFFIX, tempList, DATA_SEPARATOR);
			} else {
				logger.info("acc_ledger_file_temp表数据为空,开始生成空文件.....");
				file = new File("localUploadPath + CTR_LOAN_CONT_FILE + TXT_SUFFIX");
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();
			}
			logger.info("acc_ledger_file_temp表数据文件生成成功：" + file.getPath());
			return file;
		} catch (Exception e) {
			logger.error("acc_ledger_file_temp表数据文件生成失败:", e);
			return null;
		}
	}

	/**
	 * 新增操作
	 */
	public int insert(AccLedgerVO accLedgerVO) {// vo
		logger.debug("当前新增数据为:" + accLedgerVO.toString());
		int num = 0;
		try {
			AccLedger accLedger = new AccLedger();
			beanCopy(accLedgerVO, accLedger);
			num = accLedgerDao.insert(accLedger);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:" + num);
		return num;
	}
	
	/**
	 * 根据主键更新信息 
	 * @param inAccLedgerVO
	 * @return 
	 */  
	public int updateByPk(AccLedgerVO inAccLedgerVO) {
		logger.debug("当前修改数据为:"+ inAccLedgerVO.toString());
		int num = 0;
		try {
			AccLedger accLedger = new AccLedger();
			beanCopy(inAccLedgerVO, accLedger);
			num = accLedgerDao.updateByPk(accLedger);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inAccLedgerVO +"修改的数据条数为"+ num);
		return num;
	}
	
    /**
	 * 根据主键查询详情 
	 * @param inAccLedgerVO
	 * @return 
	 */
	public AccLedgerVO queryByPk(AccLedgerVO inAccLedgerVO) {
		logger.debug("当前查询参数信息为:"+ inAccLedgerVO);
		try {
			AccLedger queryAccLedger = new AccLedger();
			beanCopy(inAccLedgerVO, queryAccLedger);
			AccLedger queryRslAccLedger = accLedgerDao.queryByPk(queryAccLedger);
			if (Objects.nonNull(queryRslAccLedger)) {
				AccLedgerVO outAccLedgerVo = beanCopy(queryRslAccLedger, new AccLedgerVO());
				logger.debug("当前查询结果为:"+ outAccLedgerVo.toString());
				return outAccLedgerVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}
}